package com.guosen.zebra.framework.starter.ngx.internal.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.model.UploadParameter;
import com.guosen.zebra.framework.starter.ngx.model.UploadResult;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;

import java.util.HashMap;
import java.util.Map;

public class UniNgxUpload {

    /**
     * 上传文件路径
     */
    private static final String UPLOAD_PATH = "/UniExServices/restfulapi/%s%s";

    public UploadResult execute(UploadParameter uploadParameter, InvokeContext invokeContext) throws NgxException {
        String urlEncodeAccount = UrlEncodeDecoder.encode(invokeContext.getAccount());
        String urlEncodePath = UniNgxUtil.urlEncodePath(uploadParameter.getPath());
        String url = invokeContext.getAddress() + String.format(UPLOAD_PATH, urlEncodeAccount, urlEncodePath);

        Map<String, String> headers = UniNgxUtil.buildHeaders(invokeContext);
        Map<String, String> parameters = buildParameters(uploadParameter);

        JsonNode result = UniNgxRestfulClient.postWithFile(url, headers, parameters, uploadParameter.getFileContent());
        UniNgxUtil.raiseExceptionIfExist(result);

        try {
            return UniNgxUtil.getObjectMapper().treeToValue(result, UploadResult.class);
        } catch (JsonProcessingException e) {
            throw new NgxException(e);
        }
    }

    private Map<String, String> buildParameters(UploadParameter uploadParameter) {
        Map<String, String> parameters = new HashMap<>();
        UniNgxUtil.addParameter(parameters, "method", "upload");
        UniNgxUtil.addParameter(parameters, "location", uploadParameter.getLocation());
        UniNgxUtil.addParameter(parameters, "mkdirs", uploadParameter.getMkdirs());

        return parameters;
    }
}
